import os
import cv2
from flask import Flask, render_template, Response, jsonify
from datetime import datetime
from main import MonitoringSystem
from utils.alert import AlertSystem

app = Flask(__name__)

# 创建监控系统实例
monitoring_system = MonitoringSystem()
alert_system = AlertSystem()

def generate_frames():
    """生成视频流"""
    while True:
        frame = monitoring_system.camera.get_frame()
        if frame is None:
            continue

        # 进行检测
        faces = monitoring_system.face_detector.detect(frame)
        for face in faces:
            if monitoring_system.face_detector.is_stranger(face):
                alert_system.trigger_alert("检测到陌生人")

        if monitoring_system.fire_detector.detect(frame):
            alert_system.trigger_alert("检测到火灾")

        # 将图像转换为字节流
        ret, buffer = cv2.imencode('.jpg', frame)
        frame = buffer.tobytes()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/video_feed')
def video_feed():
    """视频流路由"""
    return Response(generate_frames(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/alerts')
def get_alerts():
    """获取报警历史"""
    alerts = alert_system.get_alert_history()
    return jsonify(alerts)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)